<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="TaskName" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="Please input Task Name"
          clearable
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="Start Time" prop="startTime" label-width="100px">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="Start date"
          end-placeholder="End date"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          Search
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          Reset
        </el-button>
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['sca:task:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          Create Analysis Task
        </el-button>
        <!--        <el-button
                  type="success"
                  plain
                  @click="handleExport"
                  :loading="exportLoading"
                  v-hasPermi="['sca:task:export']"
                >
                  <Icon icon="ep:download" class="mr-5px" />
                  导出
                </el-button>-->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="Task ID" align="center" prop="id" fixed="left" />
      <el-table-column label="Task Name" align="center" prop="taskName" width="200px" />
      <el-table-column label="Data Source Name" align="center" prop="datasourceId" width="240px">
        <template #default="scope">
          <div>
            {{ getDatasourceName(scope.row.datasourceId) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="Control" align="center" prop="ctrlId" width="200px">
        <template #default="scope">
          <div>
            {{ getControlName(scope.row.ctrlId) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="Remove batch effect" align="center" prop="isReduction" width="130px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.INFRA_BOOLEAN_STRING" :value="scope.row.isReduction" />
        </template>
      </el-table-column>
      <el-table-column label="Status" align="center" prop="status" width="120px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TASK_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="Start Time"
        align="center"
        prop="startTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="End Time"
        align="center"
        prop="endTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column
        label="CreateAt"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="Remarks" align="center" prop="notes" width="110px" />
      <el-table-column label="Operations" align="center" fixed="right" width="260px">
        <template #default="scope">
          <div
            style="
              display: flex;
              flex-direction: row;
              align-items: center;
              justify-content: space-around;
              width: 100%;
            "
          >
            <div v-if="scope.row['status'] === 0">
              <el-button link style="color: #529b2e" @click="startTaskMethod(scope.row)"
                >Run
              </el-button>
            </div>
            <div v-else-if="scope.row['status'] === 1">
              <el-button link style="color: #c45656">Running</el-button>
            </div>
            <div v-else-if="scope.row['status'] === 2 || scope.row['status'] === 3">
              <el-button link style="color: #65adfa" @click="showReport(scope.row)"
                >View Report
              </el-button>
              <el-button link style="color: #65adfa" @click="startTaskMethod(scope.row)"
                >ReRun
              </el-button>
            </div>
            <div>
              <el-button
                link
                type="primary"
                @click="openForm('update', scope.row.id)"
                v-hasPermi="['sca:task:update']"
              >
                Edit
              </el-button>
              <el-button
                link
                type="danger"
                @click="handleDelete(scope.row.id)"
                v-hasPermi="['sca:task:delete']"
              >
                Delete
              </el-button>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TaskForm
    ref="formRef"
    :datasource-list="datasourceList"
    :control-list="controlList"
    @success="getList"
    @refresh_datasource="getDatasourceListNoPageMethod"
  />
</template>

<script setup lang="ts" name="Task">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import download from '@/utils/download'
import * as TaskApi from '@/api/sca/task'
import * as DatasourceApi from '@/api/sca/datasource'
import * as ControlApi from '@/api/sca/control'
import TaskForm from './TaskForm.vue'
import { getDatasource, getDatasourceListNoPage } from '@/api/sca/datasource'
import { getControlList } from '@/api/sca/control'
import { ElMessage } from 'element-plus'
import { startTask, TaskVO } from '@/api/sca/task'

const { push } = useRouter() // 路由跳转
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const datasourceList = ref([]) // 数据源列表
const controlList = ref([]) // 对照组列表
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  datasourceId: null,
  taskName: null,
  ctrlId: null,
  isReduction: null,
  status: null,
  startTime: [],
  endTime: [],
  notes: null,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskApi.getTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const showReport = (taskVO: TaskVO) => {
  push('/mmtask/report/' + taskVO.id)
  // push('/product/productSpuEdit/' + taskVO.id)
}
const startTaskMethod = (taskVO: TaskVO) => {
  TaskApi.startTask({ taskId: taskVO.id }).then((res: any) => {
    getList()
    ElMessage({
      message: '提交成功',
      duration: 1000,
      type: 'success'
    })
  })
}

const getDatasourceName = (id) => {
  for (let i = 0; i < datasourceList.value.length; i++) {
    if (datasourceList.value[i]['id'] === id) {
      return datasourceList.value[i]['datasourceName']
    }
  }
}
const getControlName = (id) => {
  for (let i = 0; i < controlList.value.length; i++) {
    if (controlList.value[i]['id'] === id) {
      return controlList.value[i]['name']
    }
  }
}

const getDatasourceListNoPageMethod = async () => {
  const data = await DatasourceApi.getDatasourceListNoPage()
  datasourceList.value = data
  // console.log(datasourceList.value)
}

const getControlListMethod = async () => {
  const data = await ControlApi.getControlList()
  controlList.value = data
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TaskApi.deleteTask(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TaskApi.exportTask(queryParams)
    download.excel(data, '分析任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getDatasourceListNoPageMethod()
  getControlListMethod()
})
</script>
